import com.sun.source.tree.Tree;

public class SolutionBuildTreeByPreAndIno {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0, inorder.length-1);
    }

    int preIndex = 0;
    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int begin,int end) {
        if(begin > end) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findRootIndex(inorder,begin,end,preorder[preIndex]);
        preIndex++;

        root.left = buildTreeChild(preorder,inorder,begin,rootIndex-1);

        root.right = buildTreeChild(preorder,inorder,rootIndex+1,end);
        return root;
    }

    private int findRootIndex(int[] inorder,int begin, int end,int key) {
        for(int i = begin; i <= end; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
